package com.zqxq.file.utils;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * Created by walker on 2016/1/4.
 */
public class UploadUtil {
    //通过后缀来确定key 或者根据object来确定
    public static String getKey(Object object, String fileSuff) {
        String key = "";
        String fileName = "";
        if (StringUtils.isEmpty(fileSuff)) {//没有传参数的情况
            if (object instanceof MultipartFile) {
                MultipartFile uploadFile = (MultipartFile) object;
                fileName = uploadFile.getOriginalFilename();
            } else if (object instanceof File) {
                File uploadFile = (File) object;
                fileName = uploadFile.getName();
            }
            System.out.println("名称为：" + fileName);
            //文件后缀
            String fileTypeSuff = getSuf(fileName);
            // 生成Key
            key = UUID.randomUUID().toString() + "." + fileTypeSuff.toLowerCase();
        } else {
            key = UUID.randomUUID().toString() + "." + fileSuff.toLowerCase();
        }
        return key;
    }

    //获取后缀
    public static String getSuf(String str) {
        if (str.contains(".")) {
            str = str.substring(str.indexOf(".") + 1);
            return str;
        }
        return "";
    }

    public static String getPrefix(String str) {
        if (str.contains(".")) {
            str = str.substring(0, str.indexOf("."));
            return str;
        }
        return "";
    }
}
